import storex from '@/store/index.js';
import {
  getToken2
} from '@/common/api.js';

module.exports = (vm) => {
  uni.$u.http.interceptors.request.use(
    async (config) => {
        // 初始化配置
        config.data = config.data || {};
        config.header = config.headers || {};

        // 验证码接口特殊处理
        if (config.url && config.url.includes('/auth/getCode')) {
          config.responseType = 'arraybuffer';
        }

        // 测试
        // sessionStorage.setItem('x-auth-token', 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpZGVudGlmaWVyIjoiZG91aGFvIiwic3ViIjoiIiwiYXVkIjoiIiwiaG9zdCI6IjM2LjU2LjE5My4zOCIsImlzcyI6IiIsInR5cGUiOiJQQVNTV09SRCIsImV4cCI6MTczOTQ5NjI4NiwiaWF0IjoxNzM5NDA5ODg2fQ.ISltfwebEf4H-zIKY4diDydl8lv9Y0xlC4MlgjyLp0s')

        // token请求及其他无需鉴权接口
        const apiPaths = [
          '/auth/ythptwstoken',
          '/common/dictionary/data',
          '/common/upload/base64',
          '/problemreport/add',
          '/auth/getCode',
          '/drainage/collection/collect'
        ];

        if (apiPaths.some(path => config.url.includes(path))) {
          return config;
        }

        // 无感 token 刷新 (仅平台用户)
        if (storex.state.loginUserIdentity) {
          let now = Date.now();
          if (now >= storex.state.nextUpdateToken) {
            // 如果当前正在刷新 token，阻塞请求
            if (storex.state.isRefreshing) {
              return new Promise((resolve, reject) => {
                // 等待刷新完成
                const interval = setInterval(() => {
                  if (!storex.state.isRefreshing) {
                    clearInterval(interval);
                    if (sessionStorage.getItem('x-auth-token') != null) {
                      config.header['x-auth-token'] = sessionStorage.getItem('x-auth-token');
                    }
                    resolve(config);
                  }
                }, 100);
              });
            }

            // 开始刷新 token
            storex.commit('setIsRefreshing', true);

            try {
              const res = await getToken2({
                wstoken: storex.state.wsToken
              });
              if (res.status) {
                storex.commit('changeNextUpdateToken', Date.now() + 1200000);
                storex.commit('setIsRefreshing', false);
                if (sessionStorage.getItem('x-auth-token') != null) {
                  config.header['x-auth-token'] = sessionStorage.getItem('x-auth-token');
                }
                return config;
              } else {
                storex.commit('setIsRefreshing', false);
                return Promise.reject('Token 刷新失败');
              }
            } catch (error) {
              storex.commit('setIsRefreshing', false);
              return Promise.reject('无感刷新失败');
            }
          }
        }

        // 设置 token 到请求头
        if (sessionStorage.getItem('x-auth-token') != null) {
          config.header['x-auth-token'] = sessionStorage.getItem('x-auth-token');
        }

        return config;
      },
      (error) => {
        return Promise.reject(error);
      }
  );
};